/*
 * Twanoh Library, a useful Android utility library.
 * Copyright (C) 2006 Richard Schilling
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package gnu.org.twanoh.util;

/**
 * A class of utility functions to work on String values.
 * 
 * @author Richard Schilling (coderroadie@gmail.com)
 */
public final class StringUtil {

    /**
     * Copies string {@code s} to a new string of length {@code totalLength}. If
     * terminator is not null, then it is inserted at the end. The total length
     * will still be {@code totalLength}.
     * <p>
     * For example, calling {@code shortenString("My long string", 5, "...")}
     * returns a the string {@code "My..."}.
     * <p>
     * If s is null this function returns null.
     * <p>
     * If s is empty, this function returns an empty string;
     * 
     * @param s the string to make a shortened copy of.
     * @param totalLength the total length allowed in the resulting string
     * @param terminator a string that can be used as a terminator such as an
     *            elipsis.
     * @return a shortened string.
     */
    public static String shortenString(String s, int totalLength, String terminator) {

        if (s == null)
            throw new IllegalArgumentException("s canot be null.");

        if (s.length() == 0)
            return "";

        if (terminator != null && s.length() < terminator.length())
            return terminator.substring(0, terminator.length());

        String t = terminator == null ? "" : terminator;
        return s.substring(0, s.length() - t.length()) + t;
    }

    /**
     * Shortens a string by calling {@code shortenString(s, totalLength, null)}.
     */
    public static String shortenString(String s, int totalLength) {
        return shortenString(s, totalLength, null);
    }
}
